package com.customization.huangwm.cronJob.executeActions.SW007;

import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DBTools;
import com.customization.huangwm.utils.DateTools;
import com.customization.huangwm.utils.LogTool;
import com.engine.common.util.ServiceUtil;
import com.engine.workflow.entity.publicApi.PAResponseEntity;
import com.engine.workflow.entity.publicApi.ReqOperateRequestEntity;
import com.engine.workflow.entity.publicApi.WorkflowDetailTableInfoEntity;
import com.engine.workflow.publicApi.WorkflowRequestOperatePA;
import com.engine.workflow.publicApi.impl.WorkflowRequestOperatePAImpl;
import org.springframework.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.hrm.User;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.system.SysRemindWorkflow;
import weaver.workflow.webservices.WorkflowRequestTableField;
import weaver.workflow.webservices.WorkflowRequestTableRecord;
import weaver.workflow.workflow.WorkflowVersion;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Huangwm
 * @Date 2023-05-05
 * @Version 1.0
 * @Description TODO Work Scheduler V1 读取工作计划设定中的频率（天、周、月）及工单模板，创建工单内容提醒流程
 **/
public class WorkSchedulerV1 extends BaseCronJob {

    private static DateTools dateTools = new DateTools();
    private static DBTools dbTools = new DBTools();
    private LogTool log = new LogTool("/log/SW007/WorkSchedulerV1", false);

    public static void main(String[] args) {
        String rootPath = "E:\\WEAVER9\\ecology\\";
        GCONST.setRootPath(rootPath);
        GCONST.setServerName("ecology");

        WorkSchedulerV1 v1 = new WorkSchedulerV1();
        v1.execute();
    }

    @Override
    public void execute() {
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);

        RecordSet  rs = new RecordSet();
        RecordSet  rs2 = new RecordSet();
        String currentdate = dateTools.getCurrentDate();
        try{
            //查询符合条件的提醒数据
            String sql = "";
            if(rs.getDBType().equals("sqlserver")){
//                sql = "select * from uf_007_SchedulerV1 where (nextreminddate is null or nextreminddate='') \n" +
//                        "or (DATEDIFF ( DAY,GETDATE(),nextreminddate )=0)";
                sql = "select * from uf_007_SchedulerV1 ";
            }else{
//                sql = "select * from uf_007_SchedulerV1 where (nextreminddate is null or nextreminddate='') \n" +
//                        "or ((to_date(to_char(sysdate,'yyyy-mm-dd'),'yyyy-mm-dd')-to_date(nextreminddate,'yyyy-mm-dd'))=0)";
                sql = "select * from uf_007_SchedulerV1 ";
            }
            rs.execute(sql);
            while (rs.next()){
                String remidtype = rs.getString("remidtype");//0-天 1-周 2-月
                String remidtime = rs.getString("remidtime");//提醒周期 在remidtype基础上增加对应的时间
                String lastremiddate = rs.getString("lastremiddate");//上一次提醒日期
                String nextreminddate = rs.getString("nextreminddate");//下一次提醒日期
                String billid = rs.getString("id");
                String code = rs.getString("code");//编号
                String remidtag = rs.getString("remidtag");//提醒方式 A(只提醒)　B(帶工單模板内容提醒)　C(指定提醒流程)

                String creator = rs.getString("creator");
                String remiduser = rs.getString("remiduser");
                String dep = rs.getString("dep");
                String content1 = rs.getString("content1");

                Map<String,String> maindata = new HashMap<>();
                maindata.put("code",code);
                maindata.put("billid",billid);
                maindata.put("remidtag",remidtag);
                maindata.put("scheduleid",billid);
                maindata.put("remiduser",remiduser);
                maindata.put("creator",creator);
                maindata.put("dep",dep);
                maindata.put("content1",content1);

                if(remidtype.equals("0")){
                    //nextreminddate = dateTools.getDateFormCurrentDateToLast(creatdate,Integer.parseInt(remidtime));
                    //每天固定提醒
                    doRemind(remidtag,maindata,rs2);
                }else if(remidtype.equals("1")){
                    //每周提醒
                    String remindWeek = rs.getString("remindWeek");
                    String currWeek = dateTools.getWeekOfDate();
                    if(remindWeek.equals(currWeek)){
                        doRemind(remidtag,maindata,rs2);
                    }
                    //nextreminddate = dateTools.getDateFormCurrentDateToLast(creatdate,Integer.parseInt(remidtime)*7);
                }else if(remidtype.equals("2")){
                    //按月提醒 每个月最后一周的周五
                    //nextreminddate = dateTools.getDateFormCurrentDateToLast(creatdate,Integer.parseInt(remidtime)*30);
                    String lastWeekDay = dateTools.getLastWeekDayOfMonth();
                    if(currentdate.equals(lastWeekDay)){
                        doRemind(remidtag,maindata,rs2);
                    }
                    doRemind(remidtag,maindata,rs2);
                }else if(remidtype.equals("3")){
                    //指定日期
                    String remindDate = rs.getString("remindDate");
                    if(remindDate.equals(currentdate)){
                        doRemind(remidtag,maindata,rs2);
                    }
                }
            }
            rst.commit();
        }catch (Exception e){
            e.printStackTrace();
            rst.rollback();
        }
    }

    private void remind(Map<String,String> maindata){
        ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
        //流程流转扩展参数
        Map<String,Object> otherParams = new HashMap<>();
        otherParams.put("isVerifyPer","0"); //不验证用户创建流程权限
        otherParams.put("isnextflow","1");

        RecordSet rs = new RecordSet();
        List<Map<String,String>> detaildata = new ArrayList<>();
        rs.execute(" select * from uf_007_SchedulerV1_dt1 where mainid="+maindata.get("billid"));
        while (rs.next()){
            Map<String,String> d = new HashMap<>();
            d.put("content1",rs.getString("content1"));
            d.put("content2",rs.getString("content2"));
            d.put("content3",rs.getString("content3"));
            d.put("content4",rs.getString("content4"));
            detaildata.add(d);
        }
        BaseBean baseBean = new BaseBean();
        WorkflowVersion version = new WorkflowVersion();
        String wfid = baseBean.getPropValue("SW007","wfidB");
        int activeid = Integer.parseInt(version.getActiveVersionWFID(wfid));
        String table = dbTools.getTableNameByWfid(activeid+"");

        String  remindUser= maindata.get("remiduser");
        String[] l = remindUser.split(",");
        for(String s : l){
            maindata.put("currreminduser",s);
            requestParam.setMainData(getFormMainData(maindata));
            requestParam.setDetailData(getFormDetailData(detaildata,table+"_dt1"));
            requestParam.setWorkflowId(activeid);
            requestParam.setRequestName("工單提醒流程B "+dateTools.getCurrentDate());
            requestParam.setOtherParams(otherParams);


            WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
            User user = new User(Integer.parseInt(s));
            PAResponseEntity respose = operatePA.doCreateRequest(user,requestParam);
            if(respose.getCode().getStatusCode()>1){
                log.writeLog("自动发起情况2失败");
                log.writeLog(JSONObject.toJSONString(respose));
                throw  new RuntimeException("自动发起情况2失败");
            }else{
                String obj = JSONObject.toJSONString(respose.getData());
                JSONObject json = JSONObject.parseObject(obj);
                //return json.getString("requestid");
                log.writeLog("自动发起情况2成功");
                log.writeLog(JSONObject.toJSONString(respose));
            }
        }

    }

    private List<WorkflowRequestTableField> getFormMainData(Map<String,String> maindata) {
        List<WorkflowRequestTableField> mainFields = new ArrayList<>();

        //code
        WorkflowRequestTableField applicationUser = new WorkflowRequestTableField();
        applicationUser.setFieldName("scheduleid");
        applicationUser.setFieldValue(maindata.get("scheduleid"));
        applicationUser.setView(true);
        applicationUser.setEdit(true);
        mainFields.add(applicationUser);
        //remiduser
        WorkflowRequestTableField remiduser = new WorkflowRequestTableField();
        remiduser.setFieldName("remiduser");
        remiduser.setFieldValue(maindata.get("remiduser"));
        remiduser.setView(true);
        remiduser.setEdit(true);
        mainFields.add(remiduser);
        //creator
        WorkflowRequestTableField creator = new WorkflowRequestTableField();
        creator.setFieldName("creator");
        creator.setFieldValue(maindata.get("creator"));
        creator.setView(true);
        creator.setEdit(true);
        mainFields.add(creator);
        //dep
        WorkflowRequestTableField dep = new WorkflowRequestTableField();
        dep.setFieldName("dep");
        dep.setFieldValue(maindata.get("dep"));
        dep.setView(true);
        dep.setEdit(true);
        mainFields.add(dep);
        //content1
        WorkflowRequestTableField content1 = new WorkflowRequestTableField();
        content1.setFieldName("content1");
        content1.setFieldValue(maindata.get("content1"));
        content1.setView(true);
        content1.setEdit(true);
        mainFields.add(content1);
        //currRemindUser
        WorkflowRequestTableField currRemindUser = new WorkflowRequestTableField();
        currRemindUser.setFieldName("currreminduser");
        currRemindUser.setFieldValue(maindata.get("currreminduser"));
        currRemindUser.setView(true);
        currRemindUser.setEdit(true);
        mainFields.add(currRemindUser);

        return mainFields;
    }

    /**
     * 明细数据
     * @return
     */
    private List<WorkflowDetailTableInfoEntity> getFormDetailData(List<Map<String,String>> detaildata, String table03){
        List<WorkflowDetailTableInfoEntity> details = new ArrayList<>();
        //明细信息
        WorkflowDetailTableInfoEntity detail1 = new WorkflowDetailTableInfoEntity();
        detail1.setTableDBName(table03);
        //明细行
        WorkflowRequestTableRecord[] detailRows = new WorkflowRequestTableRecord[detaildata.size()];
        WorkflowRequestTableField field = null;
        for(int i=0;i<detaildata.size();i++){
            //明细行字段数据
            Map<String,String> data = detaildata.get(i);
            WorkflowRequestTableField[] rowDatas = new WorkflowRequestTableField[data.size()];

            int index = 0;
            for (Map.Entry<String,String> entry : data.entrySet()){
                //行字段数据
                field = new WorkflowRequestTableField();
                field.setFieldName(entry.getKey());
                field.setFieldValue(entry.getValue());
                field.setView(true);
                field.setEdit(true);
                rowDatas[index] = field;
                index ++;
            }
            WorkflowRequestTableRecord row = new WorkflowRequestTableRecord();
            row.setRecordOrder(0);
            row.setWorkflowRequestTableFields(rowDatas);
            detailRows[i] = row;
        }
        detail1.setWorkflowRequestTableRecords(detailRows);
        details.add(detail1);

        return details;
    }

    private void remind2(RecordSet rs,Map<String,String> maindata){
        ReqOperateRequestEntity requestParam = new ReqOperateRequestEntity();
        //流程流转扩展参数
        Map<String,Object> otherParams = new HashMap<>();
        otherParams.put("isVerifyPer","0"); //不验证用户创建流程权限
        otherParams.put("isnextflow","1");

        WorkflowVersion version = new WorkflowVersion();
        BaseBean baseBean = new BaseBean();
        String wfid = baseBean.getPropValue("SW007","wfidC");
        int activeid = Integer.parseInt(version.getActiveVersionWFID(wfid));

        String  remindUser= maindata.get("remiduser");
        String[] l = remindUser.split(",");
        for(String s : l){
            maindata.put("currreminduser",s);
            requestParam.setMainData(getFormMainData2(maindata));
            //requestParam.setDetailData(getFormDetailData(detaildata,table03));
            requestParam.setWorkflowId(activeid);
            requestParam.setRequestName("工單提醒流程C "+dateTools.getCurrentDate());
            requestParam.setOtherParams(otherParams);

            WorkflowRequestOperatePA operatePA = ServiceUtil.getService(WorkflowRequestOperatePAImpl.class);
            User user = new User(Integer.parseInt(s));
            PAResponseEntity respose = operatePA.doCreateRequest(user,requestParam);
            if(respose.getCode().getStatusCode()>1){
                log.writeLog("自动发起情况3失败");
                log.writeLog(JSONObject.toJSONString(respose));
                throw  new RuntimeException("自动发起情况3失败");
            }else{
                String obj = JSONObject.toJSONString(respose.getData());
                log.writeLog("自动发起情况3流程");
                log.writeLog(obj);
            }
        }
    }

    private List<WorkflowRequestTableField> getFormMainData2(Map<String,String> maindata) {
        List<WorkflowRequestTableField> mainFields = new ArrayList<>();

        //code
        WorkflowRequestTableField applicationUser = new WorkflowRequestTableField();
        applicationUser.setFieldName("scheduleid");
        applicationUser.setFieldValue(maindata.get("scheduleid"));
        applicationUser.setView(true);
        applicationUser.setEdit(true);
        mainFields.add(applicationUser);
        //remiduser
        WorkflowRequestTableField remiduser = new WorkflowRequestTableField();
        remiduser.setFieldName("remiduser");
        remiduser.setFieldValue(maindata.get("remiduser"));
        remiduser.setView(true);
        remiduser.setEdit(true);
        mainFields.add(remiduser);
        //creator
        WorkflowRequestTableField creator = new WorkflowRequestTableField();
        creator.setFieldName("creator");
        creator.setFieldValue(maindata.get("creator"));
        creator.setView(true);
        creator.setEdit(true);
        mainFields.add(creator);
        //dep
        WorkflowRequestTableField dep = new WorkflowRequestTableField();
        dep.setFieldName("dep");
        dep.setFieldValue(maindata.get("dep"));
        dep.setView(true);
        dep.setEdit(true);
        mainFields.add(dep);
        //content1
        WorkflowRequestTableField content1 = new WorkflowRequestTableField();
        content1.setFieldName("content1");
        content1.setFieldValue(maindata.get("content1"));
        content1.setView(true);
        content1.setEdit(true);
        mainFields.add(content1);
        //currRemindUser
        WorkflowRequestTableField currRemindUser = new WorkflowRequestTableField();
        currRemindUser.setFieldName("currreminduser");
        currRemindUser.setFieldValue(maindata.get("currreminduser"));
        currRemindUser.setView(true);
        currRemindUser.setEdit(true);
        mainFields.add(currRemindUser);

        return mainFields;
    }

    public void doRemind(String remidtag,Map<String,String> maindata,RecordSet rs) throws Exception {
        SysRemindWorkflow remind = new SysRemindWorkflow();
        BaseBean baseBean = new BaseBean();
        String V1_modeid = baseBean.getPropValue("SW007","V1_modeid");
        String V1_formid = baseBean.getPropValue("SW007","V1_formid");
        String V1_customid = baseBean.getPropValue("SW007","V1_customid");
        if(remidtag.equals("0")){
            remind.make("Work Scheduler Remind V1",
                    0, 0, 0, 0, 1,
                    maindata.get("remiduser"),
                    "<span> 您當前有工單計劃需要執行<a href='/spa/cube/index.html#/main/cube/card?type=0&modeId="+V1_modeid+"&formId="+V1_formid+"&opentype=0&customid="+V1_customid+"&viewfrom=fromsearchlist&guid=card&billid="+maindata.get("billid")+"' target='_blank' >計劃編號:"+maindata.get("code")+"</a> </span>", 0);
        }else if(remidtag.equals("1")){
            //情况B
            remind(maindata);;
        }else if(remidtag.equals("2")){
            //情况C
            remind2(rs,maindata);
        }
    }
}
